    package com.mangowang.module.login.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mangowang.lib.common.base.BaseActivity;
import com.mangowang.lib.common.bean.UserBean;
import com.mangowang.lib.common.help.UserHelper;
import com.mangowang.lib.common.net.Apis;
import com.mangowang.lib.common.net.NetworkManager;
import com.mangowang.lib.common.net.WebApis;
import com.mangowang.lib.common.net.interfaces.OnRequestCallBack;
import com.mangowang.lib.common.proto.Index;
import com.mangowang.lib.common.proto.LoginOuterClass;
import com.mangowang.lib.common.proto.MemberOuterClass;
import com.mangowang.lib.common.util.APKVersionCodeUtils;
import com.mangowang.lib.common.util.MMKVUtil;
import com.mangowang.lib.common.util.StatusBarUtil;
import com.mangowang.lib.common.util.updateutil.UpdateManager;
import com.mangowang.module.login.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.mangowang.module.login.R2;
import com.mangowang.module.login.ui.web.ui.WebViewActivity;
import com.tencent.mmkv.MMKV;
@Route(path = "/login/LoginActivity")
public  class  LoginActivity extends BaseActivity {

    @BindView(R2.id.phone_et)
    EditText loginAccountEdt;
    @BindView(R2.id.password_et)
    EditText loginPwdEdt;
    @BindView(R2.id.login_btn)
    Button loginBtn;
    @BindView(R2.id.login_cb_password)
    CheckBox loginCbPassword;
    @BindView(R2.id.forget_password_tv)
    TextView forget_password_tv;

    private long mExitTime;
    private int isrenzheng = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#FFFFFF"), true);
        setPasswordCanSee();
        setAccountEt();
        loginBtn.setOnClickListener(v -> login());
        forget_password_tv.setOnClickListener(v -> startActivity(ForgetPasswordActivity.class));
        checkVersion();
    }




    /**
     * 设置密码是否为明文显示
     */
    private void setPasswordCanSee() {
        loginCbPassword.setOnCheckedChangeListener((compoundButton, isChecked) -> {
            if (isChecked) {
                //设置为密文显示
                loginPwdEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                //设置为明文显示
                loginPwdEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            //光标在最后显示
            loginPwdEdt.setSelection(loginPwdEdt.length());
        });
    }

    private void setAccountEt() {
        loginPwdEdt.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                login();
                return true;
            }
            return false;
        });
        String phone = getIntent().getStringExtra("phone");
        if (!TextUtils.isEmpty(phone)) {
            loginAccountEdt.setText(phone);
            loginAccountEdt.setSelection(phone.length());//将光标移至文字末尾
        }
    }


    //返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void login() {
        isrenzheng = 0;
        String account = loginAccountEdt.getText().toString();
        if (TextUtils.isEmpty(account)) {
            showToast("请输入账号");
            return;
        }
        String pwd = loginPwdEdt.getText().toString();
        if (TextUtils.isEmpty(pwd)) {
            showToast("请输入密码");
            return;
        }
        showProgress();
        LoginOuterClass.Login.Builder builder = LoginOuterClass.Login.newBuilder();
        builder.setUsername(account);
        builder.setPassword(pwd);
        builder.setClient("android");
        LoginOuterClass.Login data = builder.build();
        NetworkManager.INSTANCE.post(Apis.login, data.toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                LoginOuterClass.Login resp = LoginOuterClass.Login.parseFrom(bytes);
                loginSuccess(resp);
                identification();
            }

            @Override
            public void onError(int code, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    private void identification() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                hideProgress();
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                UserBean userBean = new UserBean();
                userBean.setIs_approve(member.getIsApprove());
                userBean.setIs_bank(member.getIsBank());
                userBean.setTruename(member.getTruename());
                UserHelper.syncCurrentUserInfo(userBean);
                if (member.getIsApprove() == isrenzheng) {
                    showToast("请先进行实名认证");
                    WebViewActivity.startActivity(mContext, WebApis.Verification);
                } else {
                    if (member.getIsBank() == 0) {
                        WebViewActivity.startActivity(mContext, WebApis.bindBankCard + "?user_name=" + member.getTruename());
                    } else {
                       ARouter.getInstance().build("/main/MainActivity").navigation();
                    }
                }
                finish();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    private void loginSuccess(LoginOuterClass.Login respon) {
        showToast("登录成功");
        UserBean userBean = new UserBean();
        userBean.setKey(respon.getKey());
        userBean.setChat_id(respon.getChatId());
        userBean.setChat_pwd(respon.getChatPwd());
        userBean.setPush_id(respon.getPushId());
        UserHelper.login(userBean);
    }





    private void checkVersion() {
        Index.get_app_version_info.Builder builder = Index.get_app_version_info.newBuilder();
        builder.setClient("android");
        NetworkManager.INSTANCE.post(Apis.versionCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
                checkVerison(response);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
            }
        });

    }


    private void checkVerison(byte[] response) {
        String versionName = APKVersionCodeUtils.getVerName(mContext);
        Index.get_app_version_info versionBean = null;
        try {
            versionBean = Index.get_app_version_info.parseFrom(response);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        Log.e("mango", "checkVerison: " + versionBean);
        // 改为匹配版本号
        float serviceVersion = Float.parseFloat(versionBean.getVersion());
        float locationeVersion = Float.parseFloat(versionName);
        if (locationeVersion < serviceVersion) {
            UpdateManager.getInstance()
                    .setContext(this)
                    .setFragmentManager(getSupportFragmentManager())
                    .setUrl(versionBean.getDownloadUrl())
                    .setIsforce(versionBean.getForce())
                    .setContent(versionBean.getContext())
                    .start();
        }
    }




}